package cn.bjit.mq;

import cn.bjit.model.CouponRecordMessage;
import cn.bjit.service.CouponRecordService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
//监听死信队列
public class CouponMQListener {
    @Resource
    private CouponRecordService couponRecordService;
    @RabbitHandler
    public void releaseCouponRecord(CouponRecordMessage recordMessage, Message message, Channel channel) throws IOException {
        log.info("监听到要消费的消息recordMessage={}", recordMessage);
        //1，获取当前消息的id
        long msgTag = message.getMessageProperties().getDeliveryTag();
        //2,释放优惠券记录
        boolean flag = couponRecordService.releaseCouponRecord(recordMessage);
        try {
            if (flag) {
                //确定消息消费成功
                channel.basicAck(msgTag, false);
            } else {
                log.error("优惠券释放失败{}", recordMessage);
            }
        } catch (IOException e) {
            log.error("优惠券释放异常{}",e);
            channel.basicReject(msgTag,true);
        }
    }
}
